import os
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter
import numpy as np

class SensorDataProcess:
    def __init__(self):
        pass

    def read_data_from_file(self):
        # 获取当前工作目录
        file_path = os.path.join(os.getcwd(), 'MagneticData101010.txt')
        # 以只读模式打开文件
        column1 = []
        column2 = []
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                for line in file:
                    # 去除行尾的换行符，并按空格分割数据
                    data = line.strip().split()
                    if len(data) == 2:
                        # 将分割后的数据转换为浮点数并添加到相应列的列表中
                        column1.append(float(data[0]))
                        column2.append(float(data[1]))
            return column1, column2
        except FileNotFoundError:
            print("未找到 MagneticData.txt 文件，请检查文件是否存在。")
            return [], []


    def GeneratePicture(self):
        num1, num2 = self.read_data_from_file()
        derivative1 = np.gradient(num1)
        derivative2 = np.gradient(num2)

 
        # 对导数数据进行平滑处理
        window_length = 11  # 窗口长度，必须为奇数
        polyorder = 3  # 多项式阶数
        smoothed_derivative1 = savgol_filter(derivative1, window_length, polyorder)
        smoothed_derivative2 = savgol_filter(derivative2, window_length, polyorder)

        # 创建一个图形窗口
        plt.figure(figsize=(10, 6))

        # 绘制平滑后的导数曲线
        plt.plot(smoothed_derivative1, label='Smoothed Derivative of column1', color='blue')
        # 取消注释下面一行以绘制 column2 的导数曲线
        # plt.plot(smoothed_derivative2, label='Smoothed Derivative of column2', color='red')

        # 添加标题
        plt.title('Smoothed Derivatives of column1 and column2')

        # 添加 x 轴标签
        plt.xlabel('Index')

        # 添加 y 轴标签
        plt.ylabel('Derivative Value')

        # 显示图例
        plt.legend()

        # 显示网格线
        plt.grid(False)

        # 显示图形
        plt.show()

    def run(self):
        self.GeneratePicture()

if __name__ == "__main__":
    data_process = SensorDataProcess()
    data_process.run()